package com.heather.exam.controller.user;

import com.heather.exam.pojo.Result;
import com.heather.exam.pojo.table.User;
import com.heather.exam.pojo.vo.LoginVo;
import com.heather.exam.service.UserService;
import com.heather.exam.until.JwtUtils;
import com.heather.exam.until.StingUtilHkj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@RestController
public class UserController {

    @Autowired
    UserService userService;

    // 登录页面
    @PostMapping("/api/user/login")//若不封为对象最好还是用表单传输
    public Result login(@RequestBody LoginVo loginVo){
        String username = loginVo.getUsername();
        String password = loginVo.getPassword();
        System.out.println(username+"&"+password);
        String pass = StingUtilHkj.MD5(password);
        User e = userService.Login(username,pass);
        if (e != null) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("username", e.getUsername());
            claims.put("email", e.getEmail());
            claims.put("user_id", e.getId());
            claims.put("user_roomid",e.getUser_status());
            claims.put("user_role",e.getRoleId());

            // 创建一个Calendar实例，设置为当前时间加上30分钟
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MINUTE, 60);
            Date expirationDate = calendar.getTime();

            // 将过期时间添加到claims中
            claims.put("exp", expirationDate);

            // 生成包含过期时间的JWT
            String jwt = JwtUtils.generateJwt(claims);
            System.out.println(jwt);
            return Result.success(jwt);
        }
        return Result.success(e);
    }

    // 用户登录
    @RequestMapping(value = "/loginIn", method = RequestMethod.POST)
    public String loginIn(@RequestParam String username, @RequestParam String password) {
        // 调用UserService的Login方法进行登录验证
        User user = userService.Login(username, password);

        if (user != null) {
            //1为学生，2为老师，3为管理员
            if (user.getRoleId() == 1) {
                // 学生登录成功，跳转到主页
                return "Index";
            } else {
                // 老师登录成功，跳转到主页
                return "index";
            }
        } else {
            // 登录失败，返回错误页面
            return "error";
        }
    }

    // 注册页面
    @RequestMapping("/signup1")
    public String signUpPage() {
        return "signup";
    }

    // 用户注册
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public Result signUp(@RequestParam String username, @RequestParam String password, @RequestParam int role) {
        // 调用UserService的Insert方法进行用户注册
        userService.Insert(username, password, role);

        return Result.success();
    }
}

